# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jshin

import json
import os
import re
from enum import IntEnum

from recordclass import recordclass
from coin.strategy.mm.subscription import SubscriptionRequest


def clean_json(string):
  string = re.sub(r'#.*$', '', string, flags=re.M)
  string = re.sub(r'//.*$', '', string, flags=re.M)
  string = re.sub(",[ \t\r\n]+}", "}", string)
  string = re.sub(",[ \t\r\n]+\]", "]", string)
  return string


def load_clean_json(filename):
  assert os.path.exists(filename), filename
  config = None
  with open(filename) as f:
    config = json.loads(clean_json(f.read()))
  return config


PassAggExchangeMap = recordclass('PassAggExchangeMap', ['passive', 'aggressive'])


class PassAgg(IntEnum):
  PASSIVE = 0
  AGGRESSIVE = 1


def parse_subreq_config(common_config):
  trade_subreq = SubscriptionRequest.from_dict(common_config['trade_subreq'])
  if 'trade_feed_subreq' in common_config:
    trade_feed_subreq = SubscriptionRequest.from_dict(common_config['trade_feed_subreq'])
  else:
    trade_feed_subreq = trade_subreq
  if 'ref_feed_subreq' in common_config:
    ref_feed_subreq = SubscriptionRequest.from_dict(common_config['ref_feed_subreq'])
  elif 'ref_subreq' in common_config:
    ref_feed_subreq = SubscriptionRequest.from_dict(common_config['ref_subreq'])
  else:
    raise ValueError(common_config)
  return trade_subreq, trade_feed_subreq, ref_feed_subreq


def parse_subreq_config2(common_config):
  trade_subreq = SubscriptionRequest.from_dict(common_config['trade_subreq'])
  if 'trade_feed_subreq' in common_config:
    trade_feed_subreq = SubscriptionRequest.from_dict(common_config['trade_feed_subreq'])
  else:
    trade_feed_subreq = trade_subreq
  if 'ref_feed_subreqs' in common_config:
    ref_feed_subreqs = [
        SubscriptionRequest.from_dict(subreq) for subreq in common_config['ref_feed_subreqs']
    ]
  elif 'ref_subreq' in common_config:
    ref_feed_subreqs = [
        SubscriptionRequest.from_dict(subreq) for subreq in common_config['ref_subreq']
    ]
  else:
    raise ValueError(common_config)
  return trade_subreq, trade_feed_subreq, ref_feed_subreqs


def parse_feed_subreqs_config(feed_subreqs_config):
  if feed_subreqs_config is None:
    return None
  feed_subreqs = []
  for feed_subreq_config in feed_subreqs_config:
    feed_subreq = SubscriptionRequest.from_dict(feed_subreq_config)
    feed_subreqs.append(feed_subreq)
  assert len(feed_subreqs) >= 1
  return feed_subreqs
